<?php

/**
 * @author kevin
 * @date 2016-01-16 14:00:00
 * @desc 购物车操作
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}
$version = '1.0';   //版本号

if ($_POST['api_version'] != $version)      //网店的接口版本低
{
	api_err('0x008', 'a low version api');
}
if(empty($_POST['st'])){
	api_err('0x008', 'param st is Missing');
}
//用户ID检测
if(!isset($GLOBALS['uid'])){
	api_err('0x015', 'You have not logged on');
}
$user_id = $GLOBALS['uid'];
//购物车列表
if($_POST['st'] == 'list'){
	$goods_list = get_cart_goodsv1($user_id);
    $gift_count = 0;
	$data['list'] = get_cart_list($goods_list['goods_list']);
    foreach($data['list'] as $key=>$value){
        $gift = get_cart_goodsv1($user_id, $value['cart_id']);
        foreach($gift['goods_list'] as $value){
            $gift_count += intval($value['goods_number']);
        }
        $data['list'][$key]['gift'] = get_cart_list($gift['goods_list']);
    }
    $goods_list['total']['total_count'] = $goods_list['total']['goods_count'];// + $gift_count;
	$data['summary'] = $goods_list['total'];
}
//添加购物车
if($_POST['st'] == 'add'){
	$goods_id = abs(intval($_POST['goods_id']));
	$number = abs(intval($_POST['number']));
    add_cart_action($user_id, $goods_id, $number);
	$data = array();
}
//再次购买添加购物车
if($_POST['st'] == 'readd'){
	$order_id = isset($_POST['order_id']) ? abs(intval($_POST['order_id'])) : 0;
	$numbers = isset($_POST['numbers']) ? trim($_POST['numbers']) : '';
	if(empty($order_id)){
		api_err('0x008', 'param order_id can not empty');
	}
    if(!empty($numbers)){
        $numbers = json_decode(base64_decode($numbers), true);
    }
	$order = get_order_detailv1($order_id, $user_id);
	/* 订单商品 */
	$goods_list = order_goodsv1($order_id);
	foreach($goods_list as $value){
        if($value['is_gift'] == 0){
            $goods_id = isset($number[$value['goods_id']])?$number[$value['goods_id']]:intval($value['goods_id']);
            $number = intval($value['goods_number']);
            add_cart_action($user_id, $goods_id, $number);
        }
	}
    $data = array();
}
//删除购物车商品
if($_POST['st'] == 'delete'){
	$cat_id = abs(intval($_POST['cart_id']));
	if(empty($cat_id)){
		api_err('0x008', 'param cart_id can not empty');
	}
    flow_drop_cart_goods($cat_id,$user_id);
	$data = array();
}
//购物车添加收藏
if($_POST['st'] == 'collection'){ 
	$cat_id = abs(intval($_POST['cart_id']));
	if(empty($cat_id)){
		api_err('0x008', 'param cart_id can not empty');
	}
	$goods_list = get_cart_goodsv1($user_id);
    if(empty($goods_list['goods_list'])){
        api_err('0x008', 'the cart is empty.');
    }
    $info = array();
    foreach($goods_list['goods_list'] as $value){
        if($value['rec_id'] == $cat_id){
            $info = $value;
        }
    }
    if(empty($info)){
        api_err('0x800', 'param cart_id is valid.');
    }
    //收藏
    $goods_id = $info['goods_id'];
	/* 检查是否已经存在于用户的收藏夹 */
	$sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') .
		" WHERE user_id='$user_id' AND goods_id = '$goods_id'";
	if ($GLOBALS['db']->GetOne($sql) <= 0){
		/* 存入用户的收藏夹 */
		$time = gmtime();
		$sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" .
				"VALUES ('$user_id', '$goods_id', '$time')";
		if ($GLOBALS['db']->query($sql) === false){
			api_err('0x008', $GLOBALS['db']->errorMsg());
		}
	}
    //移除购物车
    flow_drop_cart_goods($cat_id,$user_id);
    $data = array();
}
//清空购物车
if($_POST['st'] == 'clear'){
    $sql = "DELETE FROM " . $ecs->table('cart') . " WHERE user_id='" .$user_id. "'";
    $GLOBALS['db']->query($sql);
	$data = array();
}
//购物车结算
if($_POST['st'] == 'checkout'){
    $list = json_decode(base64_decode($_POST['goods_list']), true);
    $flow_type = isset($_POST['flow_type'])?intval($_POST['flow_type']):CART_GENERAL_GOODS;
    if(empty($list) || !is_array($list)){
        api_err('0x008', 'param goods_list is error');
    }
    foreach($list as $value){
        $goods_id = abs(intval($value['goods_id']));
        $number = abs(intval($value['number']));
        add_cart_action($user_id, $goods_id, $number);   
    }
	//获取商品信息	
	$goods_list = get_cart_goodsv1($user_id);
	$cart_list = get_cart_list($goods_list['goods_list']);
	$data = array();
    $gift_count = 0;
	if(!empty($cart_list)){
		foreach($cart_list as $value){
            $gift = get_cart_goodsv1($user_id, $value['cart_id']);
            foreach($gift['goods_list'] as $value){
                $gift_count += intval($value['goods_number']);
            }
			$data['goods_images'][] = $value['goods_thumb'];
		}
	}
    $goods_list['total']['total_count'] = $goods_list['total']['goods_count'];// + $gift_count;
	$data['summary'] = $goods_list['total'];
	//获取用户地址信息
	$data['address'] = array();
    //获取默认地址
	$address_id  = $GLOBALS['db']->getOne("SELECT address_id FROM " .$ecs->table('users'). " WHERE user_id='$user_id'");
    //获取最近添加的地址
	if(empty($address_id)){
	    $list = get_consignee_list_v1($user_id, 1, 1);
        if(!empty($list)){
            $address_id = $list[0]['address_id'];
        }
    }
    if(!empty($address_id)){
        //获取用户收货地址
        $consignee = get_address_info($address_id, $user_id);
		$data['address'] = $consignee;
        //计算运费
        $shipping_id = get_distribution_address($user_id, $consignee);
        $order = get_post_order($user_id, $consignee, $flow_type);
        $order['shipping_id'] = $shipping_id;
        $cart_goods = cart_goodsv1($user_id, $flow_type);
        $total = order_feev1($order, $cart_goods, $consignee, $user_id);
        $data['summary']['shipping_fee'] = empty($total['shipping_fee'])?0:$total['shipping_fee'];
        $data['summary']['total_price'] = $total['goods_price'] + $total['shipping_fee'];
    }
    $data['summary']['total_price'] = strval($data['summary']['total_price']);
}
//购物车商品
if($_POST['st'] == 'goods'){}
//购物车提交
if($_POST['st'] == 'done'){
    /* 取得购物类型 */
    $flow_type = isset($_POST['flow_type'])?intval($_POST['flow_type']):CART_GENERAL_GOODS;
    $address_id = isset($_POST['address_id'])?intval($_POST['address_id']):0;
    if(empty($address_id)){
        api_err('0x008','param addresss_id can not empty.');
    }
	//检车购物车是否为空
    $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('cart') .
        " WHERE user_id = '" .$user_id . "' " .
        "AND parent_id = 0 AND is_gift = 0 AND rec_type = '{$flow_type}'";
    if ($GLOBALS['db']->getOne($sql) == 0){
		api_err('0x008', 'shopping cart can not empty');
    }
    /* 检查商品库存 */
    /* 如果使用库存，且下订单时减库存，则减少库存 */
    if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE){
        $cart_goods_stock = get_cart_goodsv1($user_id);
        $_cart_goods_stock = array();
        foreach ($cart_goods_stock['goods_list'] as $value)
        {
            $_cart_goods_stock[$value['rec_id']] = $value['goods_number'];
        }
        if(!flow_cart_stockv1($_cart_goods_stock)){
            api_err('0x008', '部分商品已卖完，立即移出购物车。');
        }
        unset($cart_goods_stock, $_cart_goods_stock);
    }
	//检查收货信息是否完整
    $consignee = get_address_info($address_id, $user_id);
    if (!check_consignee_infov1($consignee, $flow_type, $user_id)){	
		api_err('0x008', 'Receiving information is not complete');
	}
    $shipping_id = get_distribution_address($user_id, $consignee);
    if(empty($shipping_id)){
        api_err('0x008', '该地区暂时不支持配送');
    }
	//下订单、减少商品数量
    $order = get_post_order($user_id, $consignee,$flow_type);
    $order['shipping_id'] = $shipping_id;
    /* 订单中的商品 */
    $cart_goods = cart_goodsv1($user_id, $flow_type);

    if (empty($cart_goods))
    {
		api_err('0x008', 'shopping cart can not empty');
    }

    /* 检查商品总额是否达到最低限购金额 */
    if ($flow_type == CART_GENERAL_GOODS && cart_amount(true, CART_GENERAL_GOODS) < $_CFG['min_goods_amount'])
    {
		api_err('0x008', 'goods amount not enough');
    }

    /* 收货人信息 */
    foreach ($consignee as $key => $value)
    {
        $order[$key] = addslashes($value);
    }

   /* 判断是不是实体商品 */
    foreach ($cart_goods AS $val)
    {
        /* 统计实体商品的个数 */
        if ($val['is_real'])
        {
            $is_real_good=1;
        }
    }
    if(isset($is_real_good))
    {
        $sql="SELECT shipping_id FROM " . $ecs->table('shipping') . " WHERE shipping_id=".$order['shipping_id'] ." AND enabled =1"; 
        if(!$db->getOne($sql)){
		    api_err('0x008', 'shipping is not exists');
        }
    }
    /* 订单中的总额 */
    $total = order_feev1($order, $cart_goods, $consignee, $user_id);
    $order['bonus']        = $total['bonus'];
    $order['goods_amount'] = $total['goods_price'];
    $order['original_amount'] = $total['original_price'];
    $order['discount']     = $total['discount'];
    $order['surplus']      = $total['surplus'];
    $order['tax']          = $total['tax'];

    // 购物车中的商品能享受红包支付的总额
    $discount_amout = compute_discount_amountv1($user_id);
    // 红包和积分最多能支付的金额为商品总额
    $temp_amout = $order['goods_amount'] - $discount_amout;
    if ($temp_amout <= 0)
    {
        $order['bonus_id'] = 0;
    }

    /* 配送方式 */
    if ($order['shipping_id'] > 0)
    {
        $shipping = shipping_info($order['shipping_id']);
        $order['shipping_name'] = addslashes($shipping['shipping_name']);
    }
    $order['shipping_fee'] = $total['shipping_fee'];
    $order['insure_fee']   = $total['shipping_insure'];

    /* 支付方式 */
    if ($order['pay_id'] > 0)
    {
        $payment = payment_info($order['pay_id']);
        $order['pay_name'] = addslashes($payment['pay_name']);
    }
    $order['pay_fee'] = $total['pay_fee'];
    $order['cod_fee'] = $total['cod_fee'];

    /* 商品包装 */
    if ($order['pack_id'] > 0)
    {
        $pack               = pack_info($order['pack_id']);
        $order['pack_name'] = addslashes($pack['pack_name']);
    }
    $order['pack_fee'] = $total['pack_fee'];

    /* 祝福贺卡 */
    if ($order['card_id'] > 0)
	$data['list'] = get_cart_list($goods_list['goods_list']);
    {
        $card               = card_info($order['card_id']);
        $order['card_name'] = addslashes($card['card_name']);
    }
    $order['card_fee']      = $total['card_fee'];

    $order['order_amount']  = number_format($total['amount'], 2, '.', '');

    /* 如果全部使用余额支付，检查余额是否足够 */
    if ($payment['pay_code'] == 'balance' && $order['order_amount'] > 0)
    {
        if($order['surplus'] >0) //余额支付里如果输入了一个金额
        {
            $order['order_amount'] = $order['order_amount'] + $order['surplus'];
            $order['surplus'] = 0;
        }
        if ($order['order_amount'] > ($user_info['user_money'] + $user_info['credit_line']))
        {
            show_message($_LANG['balance_not_enough']);
        }
        else
        {
            $order['surplus'] = $order['order_amount'];
            $order['order_amount'] = 0;
        }
    }

    /* 如果订单金额为0（使用余额或积分或红包支付），修改订单状态为已确认、已付款 */
    if ($order['order_amount'] <= 0)
    {
        $order['order_status'] = OS_CONFIRMED;
        $order['confirm_time'] = gmtime();
        $order['pay_status']   = PS_PAYED;
        $order['pay_time']     = gmtime();
        $order['order_amount'] = 0;
    }

    $order['integral_money']   = $total['integral_money'];
    $order['integral']         = $total['integral'];

    if ($order['extension_code'] == 'exchange_goods')
    {
        $order['integral_money']   = 0;
        $order['integral']         = $total['exchange_integral'];
    }

    $order['from_ad']          = !empty($_POST['from_ad']) ? $_POST['from_ad'] : '0';
    $order['referer']          = !empty($_POST['referer']) ? addslashes($_POST['referer']) : '';

    /* 记录扩展信息 */
    if ($flow_type != CART_GENERAL_GOODS)
    {
        $order['extension_code'] = $_POST['extension_code'];
        $order['extension_id'] = $_POST['extension_id'];
    }

    $affiliate = unserialize($_CFG['affiliate']);
    if(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 1)
    {
        //推荐订单分成
        $parent_id = get_affiliate();
        if($user_id == $parent_id)
        {
            $parent_id = 0;
        }
    }
    elseif(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 0)
    {
        //推荐注册分成
        $parent_id = 0;
    }
    else
    {
        //分成功能关闭
        $parent_id = 0;
    }
    $order['parent_id'] = $parent_id;

    /* 插入订单表 */
    $error_no = 0;
    do
    {
        $order['order_sn'] = get_order_sn(); //获取新订单号
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT');

        $error_no = $GLOBALS['db']->errno();

        if ($error_no > 0 && $error_no != 1062)
        {
            api_err('0x008','订单生成失败');
        }
    }
    while ($error_no == 1062); //如果是订单号重复则重新提交数据

    $new_order_id = $db->insert_id();
    $order['order_id'] = $new_order_id;

    /* 插入订单商品 */
    $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " .
                "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id, goods_thumb, goods_img) ".
            " SELECT '$new_order_id', c.goods_id, c.goods_name, c.goods_sn, c.product_id, c.goods_number, c.market_price, ".
                "c.goods_price, c.goods_attr, c.is_real, c.extension_code, c.parent_id, c.is_gift, c.goods_attr_id, g.goods_thumb, g.goods_img".
            " FROM " .$ecs->table('cart') .' as c left join '.$ecs->table('goods').'as g on c.goods_id = g.goods_id '. 
            " WHERE c.user_id = '". $user_id ."' AND c.rec_type = '$flow_type'";
    $db->query($sql);
    /* 插入商品表的salesnum 字段，统计销量排行 */
    /*$sql = "update " . $ecs->table('goods') . " set salenum=salenum +".
           " (SELECT goods_number".
           " FROM " .$ecs->table('cart') .
           " WHERE user_id = '".$user_id."' AND rec_type = '$flow_type') where goods_id=".
           " (SELECT goods_id".
           " FROM " .$ecs->table('cart') .
           " WHERE user_id = '".$user_id."' AND rec_type = '$flow_type')";*/
    $sql = "update " .$GLOBALS['ecs']->table('goods') . " AS a, ".$GLOBALS['ecs']->table('cart') . " AS b ".
            " set a.salenum= a.salenum + b.goods_number".
            " WHERE a.goods_id=b.goods_id AND b.user_id = '".$user_id."' AND b.rec_type = '$flow_type'";
    $db->query($sql);
    /* 清空购物车 */
    clear_cartv1($user_id, $flow_type);
    /* 清除缓存，否则买了商品，但是前台页面读取缓存，商品数量不减少 */
    clear_all_files();
    /* 插入支付日志 */
    $order['log_id'] = insert_pay_log($new_order_id, $order['order_amount'], PAY_ORDER);
    $data['order_id'] = $new_order_id;
}
//st参数错误
if(!isset($data)){
	api_err('0x008', 'param st is not exists');
}
//返回数据
data_back($data, '', RETURN_TYPE);
/**
 *
 *
 *
 */
function gift_addto_cart($goods_id, $user_id, $insert_id = 0){
	$favourable_activity = get_favourable_activity($goods_id);
	if(empty($favourable_activity)){
        return false;
    }
    foreach($favourable_activity as $value){
		/* 取得优惠活动信息 */
		$act_id = intval($value['act_id']);
		$favourable = favourable_info($act_id);
		if (empty($favourable)){
			continue;
		}
		/* 判断用户能否享受该优惠 */
		if (!favourable_availablev1($favourable, $user_id)){
            continue;
		}

		/* 检查购物车中是否已有该优惠 */
		$cart_favourable = cart_favourablev1($user_id);
		if (favourable_used($favourable, $cart_favourable)){
            continue;
		}

		/* 赠品（特惠品）优惠 */
		if ($favourable['act_type'] == FAT_GOODS){
            $ids = array();
            foreach($value['gift'] as $v){
                $ids[] = $v['id'];
            }
			/* 检查是否已在购物车 */
			$sql = "SELECT goods_name" .
					" FROM " . $GLOBALS['ecs']->table('cart') .
					" WHERE user_id = '" .$user_id. "'" .
					" AND rec_type = '" . CART_GENERAL_GOODS . "'" .
					" AND is_gift = '$act_id'" .
					" AND parent_id = '$insert_id'" .
					" AND goods_id " . db_create_in($ids);
			$gift_name = $GLOBALS['db']->getCol($sql);
			if (!empty($gift_name)){
                continue;
			}

			/* 检查数量是否超过上限 */
			/*$count = isset($cart_favourable[$act_id]) ? $cart_favourable[$act_id] : 0;
			if ($favourable['act_type_ext'] > 0 && $count + count($_POST['gift']) > $favourable['act_type_ext'])
			{
				show_message($_LANG['gift_count_exceed']);
			}*/
            if($favoutable['act_type_ext'] == 0){
                $ids = $ids;
            }else{
                for($i = 0; $i < $favourable['act_type_ext']; $i++){
                    $tmp[] = $ids[$i];
                }
                $ids = $tmp;
            }
			/* 添加赠品到购物车 */
			foreach ($favourable['gift'] as $gift)
			{
				if (in_array($gift['id'], $ids))
				{
					add_gift_to_cartv1($act_id, $gift['id'], $gift['price'], $user_id, $insert_id);
				}
			}
		}
		elseif ($favourable['act_type'] == FAT_DISCOUNT)
		{
			add_favourable_to_cartv1($act_id, $favourable['act_name'], cart_favourable_amount($favourable) * (100 - $favourable['act_type_ext']) / 100, $user_id, $insert_id);
		}
		elseif ($favourable['act_type'] == FAT_PRICE)
		{
			add_favourable_to_cartv1($act_id, $favourable['act_name'], $favourable['act_type_ext'], $user_id, $insert_id);
		}
	}
    return true;
}
function favourable_availablev1($favourable, $user_id)
{
    /* 会员等级是否符合 */
    $data = get_profile($user_id);
    $user_rank = $data['rank_id'];
    if (strpos(',' . $favourable['user_rank'] . ',', ',' . $user_rank . ',') === false)
    {
        return false;
    }

    /* 优惠范围内的商品总额 */
    $amount = cart_favourable_amountv1($favourable, $user_id);

    /* 金额上限为0表示没有上限 */
    return $amount >= $favourable['min_amount'] &&
        ($amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0);
}
function cart_favourable_amountv1($favourable, $user_id)
{
    /* 查询优惠范围内商品总额的sql */
    $sql = "SELECT SUM(c.goods_price * c.goods_number) " .
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.user_id = '" . $user_id . "' " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "' " .
            "AND c.is_gift = 0 " .
            "AND c.goods_id > 0 ";

    /* 根据优惠范围修正sql */
    if ($favourable['act_range'] == FAR_ALL)
    {
        // sql do not change
    }
    elseif ($favourable['act_range'] == FAR_CATEGORY)
    {
        /* 取得优惠范围分类的所有下级分类 */
        $id_list = array();
        $cat_list = explode(',', $favourable['act_range_ext']);
        foreach ($cat_list as $id)
        {
            $id_list = array_merge($id_list, array_keys(cat_list(intval($id), 0, false)));
        }

        $sql .= "AND g.cat_id " . db_create_in($id_list);
    }
    elseif ($favourable['act_range'] == FAR_BRAND)
    {
        $id_list = explode(',', $favourable['act_range_ext']);

        $sql .= "AND g.brand_id " . db_create_in($id_list);
    }
    else
    {
        $id_list = explode(',', $favourable['act_range_ext']);

        $sql .= "AND g.goods_id " . db_create_in($id_list);
    }

    /* 优惠范围内的商品总额 */
    return $GLOBALS['db']->getOne($sql);
}

/**
 * 删除购物车中的商品
 *
 * @access  public
 * @param   integer $id
 * @return  void
 */
function flow_drop_cart_goods($id, $user_id)
{
    /* 取得商品id */
    $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('cart'). " WHERE rec_id = '$id'";
    $row = $GLOBALS['db']->getRow($sql);
    if ($row)
    {
        //如果是超值礼包
        if ($row['extension_code'] == 'package_buy')
        {
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE user_id = '" . $user_id . "' " .
                    "AND rec_id = '$id' LIMIT 1";
        }

        //如果是普通商品，同时删除所有赠品及其配件
        elseif ($row['parent_id'] == 0 && $row['is_gift'] == 0)
        {
            /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
            $sql = "SELECT c.rec_id
                    FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('group_goods') . " AS gg, " . $GLOBALS['ecs']->table('goods'). " AS g
                    WHERE gg.parent_id = '" . $row['goods_id'] . "'
                    AND c.goods_id = gg.goods_id
                    AND c.parent_id = '" . $row['goods_id'] . "'
                    AND c.extension_code <> 'package_buy'
                    AND gg.goods_id = g.goods_id
                    AND g.is_alone_sale = 0";
            $res = $GLOBALS['db']->query($sql);
            $_del_str = $id . ',';
            while ($id_alone_sale_goods = $GLOBALS['db']->fetchRow($res))
            {
                $_del_str .= $id_alone_sale_goods['rec_id'] . ',';
            }
            $_del_str = trim($_del_str, ',');

            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE user_id = '" . $user_id . "' " .
                    "AND (rec_id IN ($_del_str) OR parent_id = '$row[goods_id]' OR parent_id={$id})";
        }

        //如果不是普通商品，只删除该商品即可
        else
        {
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE user_id = '" . $user_id . "' " .
                    "AND rec_id = '$id' LIMIT 1";
        }

        $GLOBALS['db']->query($sql);
    }

    flow_clear_cart_alone($user_id);
}
/**
 * 删除购物车中不能单独销售的商品
 *
 * @access  public
 * @return  void
 */
function flow_clear_cart_alone($user_id)
{
    /* 查询：购物车中所有不可以单独销售的配件 */
    $sql = "SELECT c.rec_id, gg.parent_id
            FROM " . $GLOBALS['ecs']->table('cart') . " AS c
                LEFT JOIN " . $GLOBALS['ecs']->table('group_goods') . " AS gg ON c.goods_id = gg.goods_id
                LEFT JOIN" . $GLOBALS['ecs']->table('goods') . " AS g ON c.goods_id = g.goods_id
            WHERE c.user_id = '" . $user_id . "'
            AND c.extension_code <> 'package_buy'
            AND gg.parent_id > 0
            AND g.is_alone_sale = 0";
    $res = $GLOBALS['db']->query($sql);
    $rec_id = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $rec_id[$row['rec_id']][] = $row['parent_id'];
    }

    if (empty($rec_id))
    {
        return;
    }

    /* 查询：购物车中所有商品 */
    $sql = "SELECT DISTINCT goods_id
            FROM " . $GLOBALS['ecs']->table('cart') . "
            WHERE user_id = '" . $user_id . "'
            AND extension_code <> 'package_buy'";
    $res = $GLOBALS['db']->query($sql);
    $cart_good = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $cart_good[] = $row['goods_id'];
    }

    if (empty($cart_good))
    {
        return;
    }

    /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
    $del_rec_id = '';
    foreach ($rec_id as $key => $value)
    {
        foreach ($value as $v)
        {
            if (in_array($v, $cart_good))
            {
                continue 2;
            }
        }

        $del_rec_id = $key . ',';
    }
    $del_rec_id = trim($del_rec_id, ',');

    if ($del_rec_id == '')
    {
        return;
    }

    /* 删除 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') ."
            WHERE session_id = '" . $user_id . "'
            AND rec_id IN ($del_rec_id)";
    $GLOBALS['db']->query($sql);
}
/**
 * 取得购物车中已有的优惠活动及数量
 * @return  array
 */
function cart_favourablev1($user_id)
{
    $list = array();
    $sql = "SELECT is_gift, COUNT(*) AS num " .
            "FROM " . $GLOBALS['ecs']->table('cart') .
            " WHERE session_id = '" . $user_id . "'" .
            " AND rec_type = '" . CART_GENERAL_GOODS . "'" .
            " AND is_gift > 0" .
            " GROUP BY is_gift";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $list[$row['is_gift']] = $row['num'];
    }

    return $list;
}
/**
 * 购物车中是否已经有某优惠
 * @param   array   $favourable     优惠活动
 * @param   array   $cart_favourable购物车中已有的优惠活动及数量
 */
function favourable_used($favourable, $cart_favourable)
{
    if ($favourable['act_type'] == FAT_GOODS)
    {
        return isset($cart_favourable[$favourable['act_id']]) &&
            $cart_favourable[$favourable['act_id']] >= $favourable['act_type_ext'] &&
            $favourable['act_type_ext'] > 0;
    }
    else
    {
        return isset($cart_favourable[$favourable['act_id']]);
    }
}
/**
 * 添加优惠商品到购物车
 */
function add_gift_to_cartv1($act_id, $id, $price, $user_id, $insert_id=0)
{
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . " (" .
                "user_id, goods_id, goods_sn, goods_name, market_price, goods_price, ".
                "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ".
            "SELECT '{$user_id}', goods_id, goods_sn, goods_name, market_price, ".
                "'$price', 1, is_real, extension_code, '{$insert_id}', '$act_id', '" . CART_GENERAL_GOODS . "' " .
            "FROM " . $GLOBALS['ecs']->table('goods') .
            " WHERE goods_id = '$id'";
    $GLOBALS['db']->query($sql);
}
/**
 * 添加优惠商品到购物车
 */
function add_favourable_to_cartv1($act_id, $act_name, $amount, $user_id, $insert_id=0)
{
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . "(" .
                "user_id, goods_id, goods_sn, goods_name, market_price, goods_price, ".
                "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ".
            "VALUES('{$user_id}', 0, '', '$act_name', 0, ".
                "'" . (-1) * $amount . "', 1, 0, '', {$insert_id}, '$act_id', '" . CART_GENERAL_GOODS . "')";
    $GLOBALS['db']->query($sql);
}
function get_cart_list($goods_list){
    $return = array();
    if(empty($goods_list)){
        return $return;
    }
	foreach($goods_list as $value){
		$return[] = array(
			'cart_id'=>$value['rec_id'],
			'goods_id'=>$value['goods_id'],
			'goods_sn'=>$value['goods_sn'],
			'goods_name'=>$value['goods_name'],
			'market_price'=>$value['market_price'],
			'goods_price'=>$value['goods_price'],
			'goods_number'=>$value['goods_number'],
			'goods_thumb'=>$value['goods_thumb'],
		);
    }
    return $return;
}
/**
 * 检查订单中商品库存
 *
 * @access  public
 * @param   array   $arr
 *
 * @return  boolean
 */
function flow_cart_stockv1($arr, $user_id)
{
    foreach ($arr AS $key => $val){
        $val = intval(make_semiangle($val));
        if ($val <= 0 || !is_numeric($key)){
            continue;
        }

        $sql = "SELECT `goods_id`, `goods_attr_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart').
               " WHERE rec_id='$key' AND user_id='" . $user_id . "'";
        $goods = $GLOBALS['db']->getRow($sql);

        $sql = "SELECT g.goods_name, g.goods_number, c.product_id ".
                "FROM " .$GLOBALS['ecs']->table('goods'). " AS g, ".
                    $GLOBALS['ecs']->table('cart'). " AS c ".
                "WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'";
        $row = $GLOBALS['db']->getRow($sql);

        //系统启用了库存，检查输入的商品数量是否有效
        if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy'){
            if ($row['goods_number'] < $val){
                return false;
            }

            /* 是货品 */
            $row['product_id'] = trim($row['product_id']);
            if (!empty($row['product_id'])){
                $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $row['product_id'] . "'";
                $product_number = $GLOBALS['db']->getOne($sql);
                if ($product_number < $val){
                    return false;
                }
            }
        }elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy'){
            //检查礼包库存
            if (judge_package_stock($goods['goods_id'], $val)){
                return false;
            }
        }
    }
    return true;
}
/**
 * 获得用户的可用积分
 *
 * @access  private
 * @return  integral
 */
function flow_available_pointsv1($user_id)
{
    $sql = "SELECT SUM(g.integral * c.goods_number) ".
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.user_id = '" . $user_id . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";

    $val = intval($GLOBALS['db']->getOne($sql));

    return integral_of_value($val);
}
function add_cart_action($user_id, $goods_id, $number){
	if(empty($goods_id) || empty($number)){
		api_err('0x008', 'param goods_id or number is error');
	}
	//规格值对应的id数组
	$sql = "SELECT a.attr_id, a.attr_name, a.attr_type, ".
            "g.goods_attr_id, g.attr_value, g.attr_price " .
        'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' .
        'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' .
        "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods_id . "' " .
        'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
     $res = $GLOBALS['db']->getAll($sql);
	 $spe_arr = array();
	 if (!empty($res)){
		foreach ($res AS $row){
			$spe_arr[] = array(
				'attr_type' => $row['attr_type'],
				'name' => $row['attr_name'],
				'attr_id' => $row['attr_id'],
				'values' =>array(
					array(
						'label'        => $row['attr_value'],
						'price'        => $row['attr_price'],
						'format_price' => price_format($row['attr_price'], false),
						'id'           => $row['goods_attr_id']
					)
				)
			);
		}
    }
	//添加到购物车
	if(!$re = addto_cartv1($goods_id, $user_id, $number, $spe_arr, 0)){
		api_err('0x008', 'Add cart failed');
	}
	//赠品处理
    if(is_numeric($re)){
	    gift_addto_cart($goods_id, $user_id, $re);
    }
}
//取得配送列表 
function get_distribution_address($user_id, $consignee){
    $region = array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']);
    $shipping_list     = available_shipping_list($region);
    //$cart_weight_price = cart_weight_pricev1($user_id, $flow_type);var_dump($cart_weight_price);exit;
    return $shipping_list[0]['shipping_id'];
}
//获取post信息
function get_post_order($user_id,$consignee, $flow_type){
    $pay_id = empty($_POST['payment'])?3:$_POST['payment'];
    $order = array(
        'shipping_id'     => intval($_POST['shipping']),
        'pay_id'          => intval($payment),
        'pack_id'         => isset($_POST['pack']) ? intval($_POST['pack']) : 0,
        'card_id'         => isset($_POST['card']) ? intval($_POST['card']) : 0,
        'card_message'    => trim($_POST['card_message']),
        'surplus'         => isset($_POST['surplus']) ? floatval($_POST['surplus']) : 0.00,
        'integral'        => isset($_POST['integral']) ? intval($_POST['integral']) : 0,
        'bonus_id'        => isset($_POST['bonus']) ? intval($_POST['bonus']) : 0,
        'need_inv'        => empty($_POST['need_inv']) ? 0 : 1,
        'inv_type'        => $_POST['inv_type'],
        'inv_payee'       => trim($_POST['inv_payee']),
        'inv_content'     => $_POST['inv_content'],
        'postscript'      => trim($_POST['postscript']),
        'how_oos'         => isset($_LANG['oos'][$_POST['how_oos']]) ? addslashes($_LANG['oos'][$_POST['how_oos']]) : '',
        'need_insure'     => isset($_POST['need_insure']) ? intval($_POST['need_insure']) : 0,
        'user_id'         => $user_id,
        'add_time'        => gmtime(),
        'order_status'    => OS_UNCONFIRMED,
        'shipping_status' => SS_UNSHIPPED,
        'pay_status'      => PS_UNPAYED,
        'agency_id'       => get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']))
    );

    /* 扩展信息 */
    if (isset($flow_type) && intval($flow_type) != CART_GENERAL_GOODS)
    {
        $order['extension_code'] = $_POST['extension_code'];
        $order['extension_id'] = $_POST['extension_id'];
    }
    else
    {
        $order['extension_code'] = '';
        $order['extension_id'] = 0;
    }
    return $order;
}
